package com.googlecode.lazyrecords.chronicle;

import com.googlecode.lazyrecords.Definition;
import com.googlecode.lazyrecords.Keyword;
import com.googlecode.lazyrecords.Record;
import com.googlecode.lazyrecords.chronicle.mappings.ChronicleMapping;
import com.googlecode.lazyrecords.chronicle.mappings.ChronicleMappings;
import com.googlecode.totallylazy.Constructors;
import com.googlecode.totallylazy.Sequence;
import com.higherfrequencytrading.chronicle.Excerpt;
import com.higherfrequencytrading.chronicle.impl.IndexedChronicle;

import java.lang.reflect.Constructor;
import java.util.Iterator;

public class ChronicleSequence extends Sequence<Record> {
    private final Definition definition;
    private final IndexedChronicle chronicle;
    private final ChronicleMappings mappings;

    public ChronicleSequence(Definition definition, IndexedChronicle chronicle, ChronicleMappings mappings) {
        this.definition = definition;
        this.chronicle = chronicle;
        this.mappings = mappings;
    }

    @Override
    public Iterator<Record> iterator() {
        final Excerpt excerpt = chronicle.createExcerpt();
        return new Iterator<Record>() {
            @Override
            public boolean hasNext() {
                return excerpt.hasNextIndex();
            }

            @Override
            public Record next() {
                return toRecord(excerpt);
            }

            @Override
            public void remove() {
                throw new RuntimeException("Not done yet");
            }
        };
    }

    private Record toRecord(Excerpt excerpt) {
        Record record = Record.constructors.record();
        for (Keyword keyword : definition.fields()) {
            final ChronicleMapping<Object> mapping = mappings.get(keyword.forClass());
            record.set(keyword, mapping.read(excerpt));
        }
        return record;
    }
}
